package edu.sjsu.itack.controller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

import edu.sjsu.itack.dao.BoardDao;
import edu.sjsu.itack.dao.TackDao;
import edu.sjsu.itack.entity.Board;
import edu.sjsu.itack.entity.Tack;
import edu.sjsu.itack.entity.User;
import edu.sjsu.itack.util.ITackException; 


/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("In UploadServlet: doGet method");
		BoardDao board=new BoardDao();
		User user=(User)request.getSession().getAttribute("user");
		System.out.println(user.getUserId());
		try {
			System.out.println("In UploadServlet: doget: try");
			Board[] boardArr=board.getAllBoardsForUser((int)user.getUserId());
		
	
			request.getSession().setAttribute("boardArr", boardArr);
			request.getRequestDispatcher("uploadTack.jsp").forward(request, response);
		} catch (ITackException e) {
			System.out.println("In UploadServlet: doget: exception");
			// TODO Auto-generated catch block
			//status.append(e.getLocalizedMessage());
			request.setAttribute("error", e.getLocalizedMessage());
			request.getRequestDispatcher("uploadTack.jsp").forward(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tackName = ""; String description = ""; String filePath = "";
		int boardId = 0;
		if (request.getParameter("mode") != null){
			tackName = request.getParameter("tackName");
			description = request.getParameter("tackDesc");
			boardId = Integer.parseInt(request.getParameter("boardId"));
			filePath = request.getParameter("uploadImg");
		}
		else {
	//	File file = null ;
		int maxFileSize = 5000 * 1024;
		int maxMemSize = 5000 * 1024;
		
		// Verify the content type
		String contentType = request.getContentType();
		if ((contentType.indexOf("multipart/form-data") >= 0)) {

			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(maxMemSize);
			factory.setRepository(new File("c:\\temp"));
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax( maxFileSize );
			try {
				List<FileItem> fileItems = upload.parseRequest((HttpServletRequest)request);
				String fileName = "";
				for (FileItem fileItem : fileItems) {
					if (fileItem.isFormField()) {
						String fieldName = fileItem.getFieldName();
						if (fieldName.equals("tackName"))
							tackName = fileItem.getString();
						
						if (fieldName.equals("tackDesc"))
							description = fileItem.getString();
						
						if (fieldName.equals("boardId"))
							boardId = Integer.parseInt(fileItem.getString());
					}
					else  {
						fileName = fileItem.getName();
						filePath = request.getServletContext().getRealPath("tacks") + "\\" + fileName;
						
						//filePath = request.getServletContext().getInitParameter("tack-path") + fileItem.getName();
						File file = new File(filePath);
						try {
							fileItem.write(file);
						} catch (Exception e) {
							e.printStackTrace();
						}
						filePath = "tacks/" + fileName;
					}
				}

			} catch (FileUploadException e) {
				e.printStackTrace();
			} 
		}
	  }
		Tack tack = new Tack();
		tack.setBoardId(boardId);
		tack.setImageName(tackName);
		tack.setDescription(description);
		tack.setImagePath(filePath);
		try {
			new TackDao().createTack(tack);
		} catch (ITackException e) {
			e.printStackTrace();
		}
		request.getRequestDispatcher("board.jsp").forward(request, response);
	}
}
